/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.paris5.master2.guitarmaster.service;

import com.paris5.master2.guitarmaster.exception.EcomException;
import javax.ejb.Stateless;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

/**
 * @author mourad
 */
@Stateless(mappedName="convert")
public class ServiceConvertor implements ServiceConvertorRemote {
    
    private String wsConvertor = "http://rate-exchange.appspot.com/currency?from=:from&to=:to";
    
    @Override
    public double convert(double value, String from, String to) throws EcomException{
        double wsRate = this.getRate(from, to);
        return value * wsRate;
    }

    @Override
    public double getRate(String from, String to) throws EcomException{
        
        Double wsRate;
        
        if(from.equals(to)){
            return 1;
        }
        
        try {
            String ws = wsConvertor.replace(":from", from);
            ws = ws.replace(":to", to);
            ClientResource resource = new ClientResource(ws);
            Representation r =  resource.get();
            JsonRepresentation jr = new JsonRepresentation(r);
            JSONObject jo = jr.getJsonObject();
            wsRate = (Double) jo.get("rate");
            return wsRate.doubleValue();
        }
        catch(Exception e){
            throw new EcomException(null, e.getMessage());
        }
    }
}